package com.laikan.reader.bookstart.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.BookShelfRequester;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.ViewPagerAdapter;
import com.laikan.reader.core.utils.AccountManager;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.db.DAO;
import com.socks.library.KLog;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.laikan.reader.R.id.login_custom;

/**
 * @author 功能描述：来看引导界面activity类
 */
public class GuideActivity extends Activity implements OnClickListener {

    // 定义ViewPager对象
    private ViewPager viewPager;
    // 定义ViewPager适配器
    private ViewPagerAdapter vpAdapter;
    // 定义一个ArrayList来存放View
    private ArrayList<View> views;
    // 定义各个界面View对象
    private View view1, view2, view3;
    private LinearLayout viewPager_indicator;

    private ImageView[] mImageViews;
    private ImageView mImageView;
    private float mScale;
    private TextView custom_Login;
    private Button phone_Login, weixin_Login, other_Login;
    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;
    private TelephonyManager tm;
    private DAO dao;
    // 书架缓存列表
    private ArrayList<Book> cacheBookList;
    private String thirdtype = "1";
    private final SendAuth.Req req = new SendAuth.Req();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guide_activity1);
        /*初始化组件*/
        initView();
        initData();
        setListener();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        Constants.api = WXAPIFactory.createWXAPI(getApplicationContext(), Constants.WX_APP_ID, false);
        Constants.api.registerApp(Constants.WX_APP_ID);
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.laikan.broadcast.LOGIN");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
        // 实例化各个界面的布局对象
        LayoutInflater mLi = LayoutInflater.from(this);
        view1 = mLi.inflate(R.layout.guide_view001, null);
        view2 = mLi.inflate(R.layout.guide_view002, null);
        view3 = mLi.inflate(R.layout.guide_view003, null);
        viewPager_indicator = (LinearLayout)findViewById(R.id.viewpager_indicator);
        viewPager = (ViewPager)findViewById(R.id.viewpager);
        phone_Login = (Button)findViewById(R.id.login_phone);
        weixin_Login = (Button)findViewById(R.id.login_weixin);
        custom_Login = (TextView)findViewById(R.id.login_custom);
        other_Login = (Button)findViewById(R.id.login_other);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        dao = new DAO(this);
        // 实例化ArrayList对象
        tm = (TelephonyManager)getSystemService(this.TELEPHONY_SERVICE);
        mScale = getResources().getDisplayMetrics().density;
        views = new ArrayList<>();
        views.add(view1);
        views.add(view2);
        views.add(view3);
        mImageViews = new ImageView[3];
        for (int i = 0; i < 3; i++) {
            mImageView = new ImageView(this);
            int imageParams = (int)(mScale * 8 + 0.5f);//计算两个图片距离位置
            LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(imageParams, imageParams);
            layout.setMargins(8, 0, 8, 0);
            mImageView.setLayoutParams(layout);
            //            mImageView.setPadding(imagePadding, imagePadding, imagePadding, imagePadding);
            mImageViews[i] = mImageView;
            if (i == 0) {
                mImageViews[i].setBackgroundResource(R.drawable.point_select);
            }else {
                mImageViews[i].setBackgroundResource(R.drawable.point_unselect);
            }
            viewPager_indicator.addView(mImageViews[i]);
        }
        vpAdapter = new ViewPagerAdapter(views);
        // 设置适配器数据
        viewPager.setAdapter(vpAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                // 设置图片滚动指示器背景
                position %= views.size();
                for (int i = 0; i < mImageViews.length; i++) {
                    if (i == position) {
                        mImageViews[i].setBackgroundResource(R.drawable.point_select);
                    }else {
                        mImageViews[i].setBackgroundResource(R.drawable.point_unselect);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void setListener() {
        phone_Login.setOnClickListener(this);
        weixin_Login.setOnClickListener(this);
        other_Login.setOnClickListener(this);
        custom_Login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_phone:
                startActivity(new Intent(this, GuideLoginActivity.class));
                overridePendingTransition(R.anim.open, 0);
                break;
            case R.id.login_weixin:
                MobclickAgent.onEvent(this, "weixin_login");
                if (isWeixinAvilible(this)) {
                    thirdtype = "6";
                    // authorize(new Wechat(this));
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk_demo_test";
                    Constants.api.sendReq(req);
                    KLog.e("249 微信登录...");
                }else {
                    Toast.makeText(this, R.string.login_weixin_not_installed, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.login_other:
                startActivity(new Intent(this, OtherLoginActivity.class));
                break;
            case login_custom:
                MobclickAgent.onEvent(this,"random_num_login");
                loginToBookStore();
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        if (SPUtil.getBoolean("login_success", false)) {
            SPUtil.putBoolean("login_success", false);
            loginToBookStore();
            finish();
        }
        super.onResume();
    }

    /**
     * 微信登录广播
     */
    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            weixinLogin(code);
        }
    }

    /**
     * 微信登录
     *
     * @param code
     */
    private void weixinLogin(String code) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("name", SPUtil.getString("dsf_name", ""));
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);
        map.put("code", code);

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                parseUserInfo(httpResponse.responseContent);
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.login_wx_failed);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/thirdUserWeixin");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);


//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/thirdUserWeixin", map, null, null, requestListener);
    }

    private void parseUserInfo(String json) {
        try {
            JSONObject obj = new JSONObject(json);
            KLog.e("313 thirdLogin() json = " + json);
            String result = obj.getString("result");
            if (Constants.RESULT_OK.equals(result)) {
                JSONObject data = obj.getJSONObject("data");
                if(AccountManager.getInstance().isSwitchAccount(data.getString("token"))){
                    if(!TextUtils.isEmpty(SPUtil.getString("token", ""))){
                        AccountManager.getInstance().clearAccountData();
                    }
                }
                SPUtil.putString("token", data.getString("token"));
                SPUtil.putString("user_id", data.getString("id"));
                SPUtil.putString("user_name", data.getString("name"));
                SPUtil.putString("user_score", data.getString("score"));
                SPUtil.putString("user_level", data.getString("level"));
                SPUtil.putString("user_icon", data.getString("icon"));
                ToastMgr.showShortToast(R.string.login_success);
                MobclickAgent.onEvent(this,"laikan_login_count");
                SPUtil.putBoolean("switch_account", true);
                SPUtil.putBoolean("login_laikan_setting", true);
                BookShelfRequester.syncBookFromServer();
                dao.distributionTask();
                // 同步本地书架列表
                SPUtil.putBoolean("isGetAssetsGift", false);
                loginToBookStore();
                finish();
            }else {
                ToastMgr.showShortToast(obj.getString("error_msg"));
            }
        }catch (JSONException e) {
            ToastMgr.showShortToast(R.string.laikan_data_load_failed);
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
        this.finish();
    }

    private void loginToBookStore(){
        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra("login_type","login_custom");
        startActivity(intent);
    }
}
